package demo.dcs.util;

import demo.dcs.TraceGenerater2;
import demo.java.lang.management.jvm.AppTraceConfig;
import demo.java.lang.management.vo.ClientConstants;
import demo.java.lang.management.vo.XmlyLogSpan;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;

/**
 * 提供自定义log，提供在xdcs页面查询；
 */
public class DynamicLogUtil {
    private static final Logger logger = LoggerFactory.getLogger(DynamicLogUtil.class);

    private static final int MAX_KEY = 9;

    /**
     * logDetail保存详细日志信息或者不需要作为查询条件的数据放在里面，
     * dynamic为自定义的值，提供xdcs页面搜索, 会按顺序生成key，key0,key1,key2等，最多提供10个key；
     * @param logDetail
     * @param dynamic
     */
    public static void append(String logDetail, String ... dynamic) {
        append(null, null, null, null, logDetail, dynamic);
    }

    /**
     * zhanghao
     * @param appName
     * @param serviceId
     * @param eventType
     * @param logIdentity
     * @param logDetail
     * @param dynamic
     */
    private static void append(String appName, String serviceId, String eventType, String logIdentity, String logDetail, String ... dynamic) {

        try {
            XmlyLogSpan span = new XmlyLogSpan();
            span.setLevel(ClientConstants.INFO);
            span.setTraceId(TraceGenerater2.getTracer().getTraceIdThreadLocal());
            span.setSpanId(TraceGenerater2.getTracer().getSpanIdThreadLocal());
            span.setMonitorId(TraceGenerater2.getTracer().getMonitorIdThreadLocal());

            if(StringUtils.isBlank(serviceId)){
                serviceId =TraceGenerater2.getTracer().getServiceIdThreadLocal();
                if (StringUtils.isBlank(serviceId)){
                    serviceId = getServiceIdFromInterceptor();
                }
                span.setServiceId(serviceId);
            }else{
                span.setServiceId(serviceId);
            }

            span.setXmlyId(TraceGenerater2.getTracer().getXmlyIdThreadLocal());
            span.setTimestamp(System.currentTimeMillis());
            if(StringUtils.isBlank(appName)){
                span.setApp(AppTraceConfig.getLocalConfig().getAppName());
            }else{
                span.setApp(appName);
            }
            span.setHostName(AppTraceConfig.getLocalConfig().getHostName());
            span.setIp(AppTraceConfig.getLocalConfig().getIp());
            span.setLogDetail(logDetail);
            span.setEventType(eventType);
            span.setProcessId(AppTraceConfig.getLocalConfig().getProcessId());
            span.setLogIdentity(logIdentity);


            Map<String,String> prop = new HashMap<String,String>();
            prop.put(ClientConstants.SPAN_TYPE,ClientConstants.DYNAMICLOG);
            prop = buildDynamicParam(prop,dynamic);
            span.setProps(prop);

            TraceGenerater2.getTracer().writeLogSpan(span);
        } catch (Throwable ex) {
            logger.error("handle append error", ex);
        }
    }


    private static String getServiceIdFromInterceptor() {
        //走spring mvc interceptor
        if (SpringTraceContext.getSpringTraceContext()!=null && SpringTraceContext.getSpringTraceContext().getSpringTraceModel()!=null) {
            return SpringTraceContext.getSpringTraceContext().getSpringTraceModel().getRestUrl();
        }
        return null;
    }


    /**
     * zhanghao
     * @param dynamic
     * @return
     */
    private static Map<String,String> buildDynamicParam(Map<String,String> prop,String ... dynamic){

        int i=0;
        for(String d:dynamic){
            String key = "key"+i;
            prop.put(key,d);
            if(i > MAX_KEY){
                break;
            }
            i++;
        }

        return prop;
    }

}
